package org.platform.tool.helper;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.*;


/**
 * @author FengJie
 * @date 2018/4/12
 */
@Slf4j
@Component
public class FileHelper {
    @Autowired
    private ResourceHelper resource;

    /**
     * 创建知识文件
     *
     * @param type          申请/审核/发布
     * @param station       站点名 (无需路径和后缀名)
     * @param data          文件内容
     * @param knowledgeType 知识类型
     * @return 发布者状态
     */
    public boolean createKnowledgeFile(String type, String station, String data, String knowledgeType) throws IOException {

        String path = resource.getLocalRootDir();

        //todo 这里与监控模块交互的目录需要重新定义
        //String path = resource.getRootDir() + resource.getReceiveDir();
        //
        ////发布目录
        //if ("KnowPublish".equals(type)) {
        //    String publishPath = resource.getRootDir() + resource.getJszSendDir();
        //    switch (station) {
        //        case "Sanya":
        //            path = publishPath + resource.getSy();
        //            break;
        //        case "Miyun":
        //            path = publishPath + resource.getMy();
        //            break;
        //        default:
        //            path = publishPath + resource.getKs();
        //    }
        //}

        //知识申请目录
        String fileName = type + "_" + station + "_" + knowledgeType + "_" + System.currentTimeMillis();
        String tempFile = path + fileName + ".temp";
        String file = path + fileName + ".txt";
        if (writeFileContent(tempFile, data)) {
            return rename(tempFile, file);
        }
        return false;
    }

    /**
     * 向文件中写入内容,如果文件夹不存在,就自动创建
     *
     * @param filePath 文件路径与名称
     * @param data     写入的内容
     * @return
     * @throws IOException
     */
    public boolean writeFileContent(String filePath, String data) throws IOException {
        boolean bool = false;
        //新写入的行，换行
        String temp = "";

        FileInputStream fis = null;
        InputStreamReader isr = null;
        BufferedReader br = null;
        FileOutputStream fos = null;
        PrintWriter pw = null;
        try {
            //文件路径(包括文件名称)
            File file = new File(filePath);

            File fileParent = file.getParentFile();
            if (!fileParent.exists()) {
                fileParent.mkdirs();
            }
            file.createNewFile();
            //将文件读入输入流
            fis = new FileInputStream(file);
            isr = new InputStreamReader(fis);
            br = new BufferedReader(isr);
            StringBuffer buffer = new StringBuffer();

            //文件原有内容
            for (int i = 0; (temp = br.readLine()) != null; i++) {
                buffer.append(temp);
                // 行与行之间的分隔符 相当于“\n”
                buffer = buffer.append(System.getProperty("line.separator"));
            }
            buffer.append(data);

            fos = new FileOutputStream(file);
            pw = new PrintWriter(fos);
            pw.write(buffer.toString().toCharArray());
            pw.flush();
            bool = true;
        } catch (Exception e) {
            log.error("写入文件异常: ", e);
        } finally {
            if (pw != null) {
                pw.close();
            }
            if (fos != null) {
                fos.close();
            }
            if (br != null) {
                br.close();
            }
            if (isr != null) {
                isr.close();
            }
            if (fis != null) {
                fis.close();
            }
        }
        return bool;
    }

    /**
     * 文件重命名
     *
     * @param filePath
     * @param newFilePath
     * @return
     */
    public boolean rename(String filePath, String newFilePath) {
        File file = new File(filePath);
        File newFile = new File(newFilePath);
        return file.renameTo(newFile);
    }

    /**
     * 判断文件夹是否存在,如果存在,就创建
     *
     * @param path
     * @return
     */
    public Boolean folderExists(String path) {
        Boolean exists = true;
        File file = new File(path);
        if (!file.exists()) {
            if (file.mkdirs()) {
                log.info("[成功] 创建文件夹: " + path);
            } else {
                log.info("[失败] 创建文件夹: " + path);
                exists = false;
            }
        }
        return exists;
    }

    /**
     * 文件归档
     *
     * @throws IOException
     */
    public void copyFile(String filePath, String fileName) throws IOException {
        File source = new File(filePath);
        File dest = new File(resource.getLocalRootDir() + resource.getLocalArchivingDir() + fileName);
        org.apache.commons.io.FileUtils.copyFile(source, dest);
    }

    /**
     * 复制文件
     *
     * @param source 源路径
     * @param dest   目标路径
     * @throws IOException
     */
    public void copyFile(File source, File dest) throws IOException {
        org.apache.commons.io.FileUtils.copyFile(source, dest);
    }


}
